//
//  VVUserAccount.swift
//  Weibo
//
//  Created by 王惠平 on 2017/3/29.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit

let userAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")

class VVUserAccount: NSObject, NSCoding {
    
    //用户授权的唯一令牌
    var access_token: String?
    
    //生命周期,单位秒
    var expires_in: Int = 0 {
        
        didSet {
            
            //获取当前的时间+过期秒数 = expiresDate
           expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
            
        }
    }
    
    //根据过期描述计算过期时间对象
    var expiresDate: Date?
   
    //用户唯一id
    var uid: Int64 = 0
    
    //用户名
    var name: String?
    
    //头像地址
    var avatar_large: String?
    
    //kvc构造函数
    init(dic: [String: Any]) {
        
        super.init()
        
        setValuesForKeys(dic)
        
    }
    
    //防止字段不匹配 空实现
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
        
    }
    
    //归档和解档
    func encode(with aCoder: NSCoder) {
        
        aCoder.encode(access_token,forKey:"access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        
    }
    
    //required表示子类必须重写这个解档方法
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    
    }
    
    //保存用户对象
    func saveUserAccount() {
        
//        let userAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
    
        //归档用户对象
        NSKeyedArchiver.archiveRootObject(self, toFile: userAccountPath)
        
    }
    
    //获取本地用户对象.定义类方法使用class/static关键字使用类去调用
    class func loadUserAccount()-> VVUserAccount? {
        
        let obj = NSKeyedUnarchiver.unarchiveObject(withFile: userAccountPath)
        
        return obj as? VVUserAccount
    }
    
}
